package com.itheima.auth;

import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        Map<String,String> user = users.get(username);//模拟数据库查询
        com.itheima.pojo.User user = userService.getByUsername(username);
        List<String> list = userService.findPermissionsByUserId(user.getId());
        String[] permissions =new String[list.size()];
        list.toArray(permissions);

        if(user == null){
            return new User(username,"", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
        }
//        return new User(username, user.getPwd(),
//                AuthorityUtils.commaSeparatedStringToAuthorityList(userService.findPermissionsByUserId(user.getId())));
        return User.withUsername(username).password(user.getPwd()).authorities(permissions).build();
    }

}
